import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Textarea, Image, ScrollView, Text, Button } from '@tarojs/components'
import { AtToast, AtModal, AtModalHeader, AtModalContent, AtModalAction } from "taro-ui"
import { connect } from 'react-redux'
import classnames from 'classnames'
import { carInfo } from '@/store/car/action'
import { updateStore } from '@/store/location/action'
import CarInfo from '@/components/CarInfo'
import GoodList from '@/components/GoodsView/GoodList'
import MoreView from '@/components/GoodsView/MoreView'
import StateList from '@/components/StateList'
import CouponView from '@/components/CouponView'
import { staticUrl, concatUrl } from '@/utils'
import { getSelectedItem } from '@/api/cart'
import map from '@/utils/map'
import { getPromotion, createOrder, getPayMethod, createAnnualOrder, annualGoods, annualValid, storeInfo } from '@/api/order'
import { getJihuasuanStoreCanOrder } from '@/api/goods/details'
import { createCart } from '@/api/goods'
import { getGoodsStoreSalePrice } from '@/api/assistant'
import './index.scss'
const Checked = 'https://static3.jekunauto.com/img/others/checked.png'
const Unselected = 'https://static3.jekunauto.com/img/others/unselected.png'
import { accAdd, accMul } from '@/utils'


const couponIcon = staticUrl('/img/order/icon-ka.png')
const redpacketIcon = staticUrl('/img/order/icon-redpacket.png')
const checkIcon = staticUrl('/img/order/icon-check.png')
const iconSuc = staticUrl('/img/order/icon-success.png')

interface State {
  isCheck: boolean
  list: any
  listLoaded: boolean
  down: boolean
  promotion: any
  couponItemIds: any
  payMethod: number
  payList: any
  showPayPop: boolean
  useCouponIndex: number
  showCouponPop: boolean
  customerRemark: string
  checkedConpun: any
  showPaySuc: boolean
  orderDetails: any
  distribution: any
  radioChecked: boolean
  firstChecked: boolean
  ancardReturn: object,
  shareMobile: string,
  address: string,
  storeName: string,
  shareStoreCode: string,
  shareVendorName: string,
  superiorOpenString: string,
  shareOpenString: string,
  superiorMobile: string,
  selectStore: object,
  selectArea: object, // 年卡选择选择服务的区域
  noOprate: boolean,
  cardTips: string
  isOpened: boolean,
  staffCode: string, // 员工编码
  openedModal: Boolean,
  cartIds: any,
  isCarMaintain: Boolean, //是否养车助手
  maintainCarInfo: Object,// 养车助手车辆信息
}

@connect<any>(({ car, user, location }) => ({
  car: car.carInfo.currentCar,
  store: location.storeLocation
}), _dispatch => ({
  dispatchFetchList() {
    return _dispatch(carInfo())
  },
  dispatchStore(params) {
    return _dispatch(updateStore(params))
  },
}))
export default class Index extends Component<any> {
  $instance = getCurrentInstance();
  protected __data__: any
  constructor (props) {
    super(props)
    this.state = {
      isOpened: false,
      cardTips: '为提高您到店服务的效率，已为您自动更换了部分商品的下单门店，销售价格可能有变化',
      noOprate: true,
      isCheck: false,
      list: {},// 订单金额数据（卡券，折扣等）
      listLoaded: false,// 订单金额数据（卡券，折扣等）是否展示
      down: false,
      promotion: null,//优惠券信息
      couponItemIds: [],
      payMethod: 0,
      payList: [], // 支付方式
      showPayPop: false,
      useCouponIndex: 0,
      showCouponPop: false,
      customerRemark: '',
      checkedConpun: [],
      showPaySuc: false,
      orderDetails: {},
      distribution: { reductionPriceNumber: 0 },// 分销折扣信息
      radioChecked: false,// 是否同意年卡协议
      firstChecked: true,// 是否第一次点击年卡协议按钮
      ancardReturn: {},//上传签名图片信息
      shareMobile: '',// 分享有礼上级分享人手机号
      address: '', // 分享有礼带过来的门店地址
      storeName: '', // 分享有礼带过来的门店名
      shareStoreCode: '', // 分享有礼带过来的门店编码
      shareVendorName: '',// 分享有礼带进来的接入商名
      superiorOpenString: '', // 分享有礼带进来的上上级分享人
      shareOpenString: '', // 分享有礼带进来的上级分享人
      superiorMobile: '',// 分享有礼上上级分享人手机号
      selectStore: {}, // 选择的下单门店
      selectArea: {}, // 年卡选择服务的区域
      staffCode: '', // 员工编码
      openedModal: false,
      cartIds: [],
      isCarMaintain: false,
      maintainCarInfo: {}
    }
    this.__data__ = process.env.TARO_ENV === 'weapp' ? '__data__' : 'data'
  }


  state: State

  UNSAFE_componentWillMount() { }
  private apiLoaded: boolean = false // 是否提交订单


  async componentDidShow() {
    console.log('this.$instance.router.params', this.$instance.router.params)
    let { store, isCarMaintain = 0 } = this.$instance.router.params
    if (store) { // 存在从商品详情过来的门店数据
      this.setState({ selectStore: JSON.parse(this.$instance.router.params.store) }, () => {
        Taro.showToast({
          title: '门店已变更，商品价格可能变化！',
          icon: 'none',
          duration: 2000,
        })
      })
    }
    if (Number(isCarMaintain)) {
      console.log(isCarMaintain)
      this.setState({ isCarMaintain })
    }
    let pages = Taro.getCurrentPages();
    let currentPage = pages[pages.length - 1]; // 获取当前页面
    if (currentPage[this.__data__].selectStore) { // 获取值
      this.setState({
        selectStore: currentPage[this.__data__].selectStore,
        checkedConpun: [],
        couponItemIds: [],
        promotion: null
      })
      console.log('进来的selectStore数据', currentPage[this.__data__].selectStore)
    }
    // 存在分销折扣信息
    if (this.$instance.router.params.distribution) {
      const distribution = JSON.parse(this.$instance.router.params.distribution)
      // 如果是二级分销 需要把折扣置为0
      if (distribution.mobile !== '' && distribution.mobile2 !== '') {
        distribution.reductionPriceNumber = 0
      }
      this.setState({ distribution })
    }

    // 存在门店storeCode 使用该门店信息
    if (this.$instance.router.params.storeCode) {
      console.log('STORECODE', '会不会执行')
      console.log('this.$instance.router.params.storeCod', this.$instance.router.params.storeCod)
      Taro.setStorageSync('STORECODE', this.$instance.router.params.storeCode)
      await this.getStoreInfo() // 获取门店信息
    }

    await this.getList() // 获取订单数据
    this.apiLoaded = true

    const query = Taro.getStorageSync('ANCARD_RETURN')
    console.log('query: ', query);
    if (query && JSON.parse(query) && JSON.parse(query).time) {
      await this.setState({
        radioChecked: true,
        ancardReturn: JSON.parse(query),
        firstChecked: false
      })
    }
  }
  async UNSAFE_componentWillReceiveProps(nextProps, nextContext) { }
  componentWillUnmount() {
    // 清除是否点击确认上传图片
    Taro.removeStorageSync('ANCARD_RETURN')
  }

  async componentDidMount() {
    // 能进来这个页面的，绝对是都可以销售的
    let { storeCode = '', cityCode = '', type = 0, annualCardId, jihuasuanId, jihuasuanSource } = this.$instance.router.params
    console.log('annualCardId', annualCardId)
    let { isThoat = '' } = this.$instance.router.params
    if (isThoat) {
      console.log('执行了没有----')
      this.setState({
        isOpened: true
      }, () => {
        let _this = this
        setTimeout(() => {
          _this.setState({
            isOpened: false
          })
        }, 1500)
      })
    }
    if (storeCode) {
      let locationData = Taro.getStorageSync('CURRENT_LONGITUDE_LATITUDE')
      let storeParams: any = {
        storeCode
      }
      if (locationData) {
        const { latitude: userLatitude, longitude: userLongitude } = locationData
        locationData
        storeParams = {
          ...storeParams,
          userLongitude,
          userLatitude
        }
      } else {
        const curLocation: any = await map.getLocation()
        if (curLocation) {
          const { latitude: userLatitude, longitude: userLongitude } = curLocation
          storeParams = {
            ...storeParams,
            userLongitude,
            userLatitude
          }
        }
      }
      const result = await storeInfo(storeParams)

      const data = result.data['data']
      if (jihuasuanId) {
        // 在这里判断
        const resp = await getJihuasuanStoreCanOrder({
          goodsIds: annualCardId,
          jihuasuanId,
          jihuasuanSource,
          storeCode,
          type: 2 // 1商品  2年卡
        })
        const isCanData = resp.data['data']
        if (isCanData.can == 1) {
          this.setState({
            selectStore: data,
          })
        }
        console.log('isCanData', isCanData)
      } else {

        console.log('data门店的数据', data)
        this.setState({
          selectStore: data,
        })
      }


    }
  }

  getCanOrder() {
    let {
      storeCode = '',
      jihuasuanId,
      id,
      jihuasuanSource,
    } = this.$instance.router.params
    if (jihuasuanId) { // 集划算活动，需要判断传递进来的门店是否参与活动
      getJihuasuanStoreCanOrder({
        goodsIds: id,
        jihuasuanId,
        jihuasuanSource,
        storeCode,
        type: 2 // 1商品  2年卡
      }).then(resp => {
        if (resp.data.data.can == 1) {
          this.setState({
            selectStore: data,
          })
        }
        console.log('res', resp)
      })
    } else {
      this.setState({
        selectStore: data,
      })
    }
  }

  config = {
    navigationBarTitleText: '订单确认'
  }

  componentDidHide() { }
  componentDidCatchError() { }
  componentDidNotFound() { }

  changeCheck = (e) => {
    const { value } = e.detail
    this.setState({
      isCheck: value
    })
  }

  // 带门店code获取门店信息
  getStoreInfo = async () => {
    await storeInfo().then(async (res) => {
      console.log('res', res)
      const { data, success } = res.data
      const { dispatchStore } = this.props
      if (success) {
        await dispatchStore(data)
      }
    }).catch((err) => {
      console.log('err', err)
    })
  }

  // 获取支付方式
  getPayMethod = () => {
    const type = this.$instance.router.params.type ? this.$instance.router.params.type : 0
    let { jihuasuanId = '' } = this.$instance.router.params
    const { list, selectStore } = this.state
    let { cartList } = list
    console.log('list', list)
    console.log('items', cartList)
    console.log('selectStore', selectStore)
    let goodsIds = []
    if (cartList && cartList.length !== 0) {
      goodsIds = cartList.map(v => {
        const { id } = v.goods
        return id
      })
    }
    let params = {
      type,
      clientSource: process.env.TARO_ENV === 'weapp' ? 0 : 9,
      goodsIds,
      storeCode: selectStore.storeCode || list.latelyStoreInfo && list.latelyStoreInfo.storeCode || '', // 解决了购物车的问题
    }
    if (jihuasuanId !== '') {
      params.scene = 1
    }
    getPayMethod(params).then(res => {
      const data = res.data.data
      this.setState({
        payList: data
      })
    })
  }

  // 获取订单数据
  getList = async () => {
    const type = this.$instance.router.params.type || 0
    console.log('type', type)
    try {
      let list: any = {}
      let newCar = {}
      const car = this.props.car
      if (!car) {
        const {
          dispatchFetchList
        } = this.props
        await dispatchFetchList().then(res => {
          console.log('res', res)
          console.log('type', type)
          console.log('res.currentCar', res.currentCar)
          if (type == 1 && res && !res.currentCar) {
            Taro.showModal({
              title: '温馨提示',
              showCancel: false,
              content: '请先设置默认车辆信息',
              cancelText: '取消',
              cancelColor: '#999999',
              confirmText: '去添加',
              confirmColor: '#12b3ff',
            }).then(res => {
              // 存起来
              if (res.confirm) {
                Taro.navigateTo({
                  url: '/pages/car/add/index'
                })
              }
            })
          } else {
            console.log('有没有执行进来-----')
            const data = res.currentCar
            newCar = data
            this.handleGetListData(list, newCar, type, car)
          }
        })
      } else {
        this.handleGetListData(list, newCar, type, car)
      }
    } catch (e) {
      console.log(e)
    }
  }

  handleGetListData = async (list, newCar, type, car) => {
    // type == 1为年卡订单
    if (type) {
      // diy年卡
      let { jihuasuanId = '', jihuasuanGoodsId = '', address = '', storeName = '', shareMobile = '', superiorMobile = '', shareStoreCode = '', shareVendorName = '', superiorOpenString = '', shareOpenString = '', staffCode = '' } = this.$instance.router.params
      console.log('进来的参数', this.$instance.router.params)
      let { selectStore } = this.state
      let diyAnnual: any = this.$instance.router.params.diyAnnual
      if (diyAnnual) {
        diyAnnual = JSON.parse(diyAnnual)
        list = diyAnnual
        const result = await annualValid({
          annualCardId: 0
        })
        list.vailDay = result.data.data.vailDay
      } else {
        let params = {
          carLicense: car ? car.carLicense : newCar.carLicense,
          carId: car ? car.id : newCar.id,
          annualCardId: this.$instance.router.params.annualCardId,
        }
        if (shareStoreCode) {
          params.storeCode = shareStoreCode
        } else if (selectStore.storeCode) {
          params.storeCode = selectStore.storeCode
        }
        if (jihuasuanId) {
          params.jihuasuanId = jihuasuanId
          params.jihuasuanGoodsId = jihuasuanGoodsId
        }
        console.log('执行前面的params', params)
        const result = await annualGoods(params)
        list = result.data.data
      }
      this.setState({
        list,
        listLoaded: true,
        storeName,
        address,
        shareMobile,
        superiorMobile,
        shareStoreCode,
        shareVendorName,
        superiorOpenString,
        shareOpenString,
        staffCode
      }, () => {
        this.getPayMethod() // 获取支付方式
      })
    } else {
      let { jihuasuanId = '', jihuasuanGoodsId = '' } = this.$instance.router.params
      let { selectStore, isCarMaintain } = this.state
      let { storeCode = '' } = selectStore
      // 获取购物车商品列表及价格
      let paramsData = {
        ids: this.$instance.router.params.cartIds,
        storeCode
      }
      if (jihuasuanId) {
        paramsData.jihuasuanId = jihuasuanId
        paramsData.jihuasuanGoodsId = jihuasuanGoodsId
      }
      console.log('list11111', isCarMaintain)
      let maintainCarInfo: any = {}
      if (isCarMaintain) { // isCarMaintain 养车助手
        list = Taro.getStorageSync('CARTGOODS')
        maintainCarInfo = list.carInfo
      } else {
        const result = await getSelectedItem(paramsData)
        list = result.data.data
      }
      let code = selectStore.storeCode || list.latelyStoreInfo && list.latelyStoreInfo.storeCode || ''
      console.log('进来的code', code)
      this.setState({
        list,
        listLoaded: true,
        maintainCarInfo
      }, () => {
        this.getGoodsStoreSalePrice(code)
        this.getPromotion(code)
        this.getPayMethod() // 获取支付方式
      }
      )
      // }, () => this.getPromotion())
    }
  }

  importMark = (e) => {
    const { value } = e.detail
    this.setState({
      customerRemark: value
    })
  }

  // 获取优惠信息
  getPromotion = (storeCode) => {
    console.log('storeCode', storeCode)
    console.log('执行进来优惠券信息')
    // 必须先选择下单门店才能查看优惠券、红包等信息
    if (!storeCode) return
    const { list, couponItemIds, promotion } = this.state
    let notUseCouponItemIds = []
    if (couponItemIds.length) {
      notUseCouponItemIds = promotion.coupon.available.filter(v => !couponItemIds.includes(v.id)).map(v => v.id)
    }
    const goodsList = JSON.stringify(list.cartList.map(v => {
      return {
        goodsId: v.goods.id,
        number: v.itemNumber,
        goodsSkuId: v.goodsSku.id
      }
    }))
    console.log('notUseCouponItemIds', notUseCouponItemIds)
    console.log('couponItemIds', couponItemIds)
    let useids = JSON.stringify(couponItemIds)
    let notuseids = JSON.stringify(notUseCouponItemIds)
    // 获取优惠券信息接口
    let paramsDatas = {
      goodsList,
      couponItemIds: useids,
      notUseCouponItemIds: notuseids,
      // 订单类型(0:商品订单,1:年卡订单,2:方案单,3:定金单,4:零售单,5:保险订单)
      // 订单确认页只有商品订单、年卡订单，年卡订单不可使用红包、卡券。因此只有商品订单，定值0
      orderType: 0,
      storeCode,
    }
    let { jihuasuanId = '', jihuasuanGoodsId = '' } = this.$instance.router.params
    if (jihuasuanId) {
      paramsDatas.jihuasuanGoodsId = jihuasuanGoodsId
    }
    getPromotion(paramsDatas).then(res => {
      const data = res.data.data
      this.checkedStatus = false
      Taro.hideLoading()
      this.setState({
        promotion: data
      })
    }).catch(e => {
      this.checkedStatus = false
      Taro.hideLoading()
    })
  }

  // 查看更多
  changeGoodsStatus = (e) => {
    this.setState({
      down: e
    })
  }
  // 创建商品订单
  goodsOrder = () => {
    const carInfo = this.props.car
    const { couponItemIds, payMethod, payList, isCheck, promotion, customerRemark, distribution, selectStore, list, cartIds = [] } = this.state
    let carParams = {}
    if (carInfo) {
      carParams = {
        carLicense: carInfo.carLicense,
        carId: carInfo.id
      }
    }
    let {
      jihuasuanId,
      pMobile,
      ppMobile,
      pUnionId,
      ppUnionId,
      jihuasuanGoodsId,
      jihuasuanSource,
      thirdPartyShareSource
    } = this.$instance.router.params

    const data = {
      ...carParams,
      cartIds: this.$instance.router.params.cartIds || cartIds,
      couponItemIds,
      clientSource: process.env.TARO_ENV === 'weapp' ? 0 : 9,
      thirdPartySource: 'JEKUNAUTO',
      payMethod: payList[payMethod].value,
      redPacket: isCheck ? promotion.redPacket : 0,
      superRedPacket: isCheck ? promotion.superRedPacket : 0,
      baobeiRedPacket: isCheck ? promotion.baobeiRedPacket : 0,
      platformRedPacket: isCheck ? promotion.platformRedPacket : 0,
      customerRemark: customerRemark,
      distributionInfo: {},
      jihuasuanInfo: {}
    }

    if (distribution) {
      const distributionInfo = {
        "goodsDistributionId": distribution.goodsDistributionId,
        "mobile": distribution.mobile,
        "mobile2": distribution.mobile2,
        "storeCode": distribution.storeCode,
        'isStaff': distribution.isStaff
      }
      if (distributionInfo.mobile === distributionInfo.mobile2) {
        distributionInfo.mobile2 = ''
      }
      if (!distributionInfo.mobile) {
        delete distributionInfo.mobile2
      }


      data.distributionInfo = distributionInfo
    }
    if (jihuasuanId) {
      const jihuasuanInfo = {
        jihuasuanId,
        pMobile: pMobile || '',
        ppMobile: ppMobile || '',
        pUnionId: pUnionId || '',
        ppUnionId: ppUnionId || '',
        jihuasuanGoodsId
      }
      if (thirdPartyShareSource) {
        jihuasuanInfo.thirdPartyShareSource = thirdPartyShareSource
      }
      data.jihuasuanInfo = JSON.stringify(jihuasuanInfo)
    }
    data.storeCode = selectStore.storeCode || list.latelyStoreInfo.storeCode


    createOrder(data).then(res => {
      const data = res.data.data
      const orderNumber = data.orderNumber
      this.createOrderStatus = false
      Taro.hideLoading()
      if (Number(data.needPayPrice) === 0) {
        this.setState({
          orderDetails: data,
          showPaySuc: true
        })
      } else {
        let { selectStore } = this.state
        // 普通商品、保养助手商品，只可以在线支付
        if (payList[payMethod].value === 'online') { // 在线支付
          Taro.redirectTo({
            url: `/pages/order/pay/index?orderNumber=${orderNumber}&shareStoreCode=${selectStore.storeCode ? selectStore.storeCode : ''}&jihuasuanId=${jihuasuanId ? jihuasuanId : ''}`
          })
        } else if (payList[payMethod].value === 'offline') { // 线下支付
          this.setState({
            orderDetails: data,
            showPaySuc: true
          })
        }
      }
    }).catch(e => {
      this.createOrderStatus = false
      Taro.hideLoading()
    })
  }
  // 创建年卡订单
  annualOrder = async () => {
    console.log('this.$instance.router.params', this.$instance.router.params)
    let {
      jihuasuanId,
      pMobile,
      ppMobile,
      pUnionId,
      ppUnionId,
      jihuasuanGoodsId,
      jihuasuanSource,
      thirdPartyShareSource
    } = this.$instance.router.params
    const { selectStore, couponItemIds, payList, payMethod, list, promotion, isCheck, customerRemark, ancardReturn, shareMobile, shareStoreCode, superiorOpenString, shareOpenString, superiorMobile, staffCode } = this.state
    console.log('shareStoreCode', shareStoreCode)
    const carInfo = this.props.car
    const annualCardList: any = {
      annualCardType: list.annualCardType,
      annualCardId: list.annualCardId,
      items: list.items.map(goods => {
        const { goodsId, annualCardPrice, type: goodsType, eachUse, relatedNum, buyNum } = goods
        return {
          goodsId,
          annualCardPrice,
          goodsType,
          eachUse,
          relatedNum,
          buyNum
        }
      })
    }

    if (this.$instance.router.params.diyAnnual) {
      // diy年卡需要传年卡名称
      annualCardList.annualCardName = list.annualCardName
    }

    try {
      let carParams = {}
      if (carInfo) {
        carParams = {
          carLicense: carInfo.carLicense,
          carId: carInfo.id
        }
      }
      // Taro.hideLoading()
      let params = {
        annualCardList,
        type: 1,
        couponItemIds,
        redPacket: isCheck ? promotion.redPacket : 0,
        customerRemark: customerRemark,
        ...carParams,
        payMethod: payList[payMethod].value,
        imageId: ancardReturn.imageId,
        storeCode: selectStore.storeCode,
        clientSource: process.env.TARO_ENV === 'weapp' ? 0 : 9
      }
      if (shareMobile) params.shareMobile = shareMobile
      if (superiorMobile) params.superiorMobile = superiorMobile
      params.storeCode = selectStore.storeCode
      if (shareStoreCode) params.storeCode = shareStoreCode

      if (shareOpenString) params.shareOpenString = shareOpenString
      if (superiorOpenString) params.superiorOpenString = superiorOpenString

      if (staffCode) params.shareStaffCode = staffCode
      if (staffCode && this.$instance.router.params.storeCode) params.shareStoreCode = this.$instance.router.params.storeCode
      //
      if (jihuasuanId) {
        const jihuasuanInfo = {
          jihuasuanId,
          pMobile: pMobile || '',
          ppMobile: ppMobile || '',
          pUnionId: pUnionId || '',
          ppUnionId: ppUnionId || '',
          jihuasuanGoodsId,
          thirdPartyShareSource
        }
        params.jihuasuanInfo = JSON.stringify(jihuasuanInfo)
      }
      const result = await createAnnualOrder(params)
      this.createOrderStatus = false
      const data = result.data.data
      const orderNumber = data.orderNumber
      // 年卡订单支持在线支付、到店支付
      if (payList[payMethod].value === 'online') {
        Taro.redirectTo({
          url: `/pages/order/pay/index?orderNumber=${orderNumber}&shareStoreCode=${shareStoreCode ? shareStoreCode : ''}&platform=1`
        })
      }
      if (payList[payMethod].value === 'offline') {
        Taro.redirectTo({
          url: '/pages/order/details/index?orderNumber=' + orderNumber
        })
      }
    } catch (e) {
      this.createOrderStatus = false
      // Taro.hideLoading()
      console.log(e)
    }
  }

  private createOrderStatus: boolean = false
  // 提交订单
  sendOrder = (e) => {
    const type = this.$instance.router.params.type ? this.$instance.router.params.type : 0
    const jihuasuanId = this.$instance.router.params.jihuasuanId ? this.$instance.router.params.jihuasuanId : ''
    const isAnnaul = type > 0
    const { radioChecked, selectStore, address } = this.state
    if (!jihuasuanId && isAnnaul && radioChecked == false) {
      return Taro.showToast({
        title: '请先勾选提交订单前阅读并确认《年卡协议》',
        icon: 'none',
        duration: 1800
      })
    }
    if (!this.apiLoaded) return
    if (this.createOrderStatus) return
    this.createOrderStatus = true
    // type == 1是年卡订单
    console.log(e)
    Taro.showLoading({ title: '提交中' })
    if (type > 0) {
      // 创建年卡订单
      if (!address && !this.$instance.router.params.storeName && !selectStore.storeCode) {
        Taro.showToast({
          title: '请先选择下单门店！',
          icon: 'none',
          duration: 2000
        })
        this.createOrderStatus = false
        return
      }
      //集划算活动下单门店二次确认
      if (jihuasuanId && !e) {
        Taro.hideLoading()
        this.createOrderStatus = false
        this.setState({
          openedModal: true
        })
        return
      }
      this.annualOrder()
    } else {
      let { selectStore, list, isCarMaintain } = this.state
      console.log('selectStore.storeCode', selectStore)

      if (!selectStore.storeCode && !list.latelyStoreInfo) {
        Taro.showToast({
          title: '请先选择下单门店！',
          icon: 'none',
          duration: 2000
        })
        this.createOrderStatus = false
        return
      }
      //集划算活动下单门店二次确认
      if (jihuasuanId && !e) {
        Taro.hideLoading()
        this.createOrderStatus = false
        this.setState({
          openedModal: true
        })
        return
      }
      //养车助手
      if (isCarMaintain) {
        this.createMaintainOrder()
        return
      }
      // 创建商品订单
      this.goodsOrder()
    }
  }

  // 创建养车助手订单
  createMaintainOrder() {
    let { list, selectStore } = this.state
    let goodsData: any = []
    list.cartList.forEach(e => {
      goodsData.push({
        goodsId: e.goodsId,
        goodsSkuId: e.defaultGoodsSkuId,
        number: e.number,
        directBuy: 1,
        itemType: 1
      })
    })
    createCart({
      goodsData: JSON.stringify(goodsData),
      storeCode: selectStore.storeCode
    }).then(res => {
      const data = res.data.data
      this.setState({
        cartIds: data.cartIds
      }, () => {
        this.goodsOrder()
      })
    })
  }
  // 养车助手获取商品价格
  getGoodsStoreSalePrice(storeCode) {
    let { list, isCarMaintain } = this.state
    if (!storeCode || !isCarMaintain) return
    let goodsItems: any = []
    list.cartList.forEach(e => {
      goodsItems.push({
        goodsId: e.goodsId,
        goodsSkuId: e.defaultGoodsSkuId
      })
    })
    getGoodsStoreSalePrice({
      goodsItems,
      storeCode
    }).then(res => {
      let data = res.data.data
      let totalPrice = 0
      list.cartList.forEach(e => {
        let findIndex = data.findIndex(v => v.goodsId == e.goodsId)
        if (findIndex >= 0) {
          e.itemPrice = data[findIndex].salePrice
        }
        totalPrice = accAdd(Number(totalPrice), accMul(e.itemPrice, e.number))
      })
      list.totalPrice = totalPrice
      console.log(list)
      this.setState({ list })
    })
  }

  closeOpenedModal() {
    this.setState({
      openedModal: false
    })
  }

  // 切换支付方式
  changePayIndex = (i: number) => {
    const { payMethod } = this.state
    if (payMethod === i) return
    this.setState({
      payMethod: i
    })
  }

  // 优惠券弹窗tab切换
  tabCouponTag = (index: number) => {
    this.setState({
      useCouponIndex: index
    })
  }

  private checkedStatus: boolean = false
  // 勾选优惠券
  checkedCoupon = (coupon, canSelect) => {
    console.log('coupon', coupon)
    console.log('canSelect', canSelect)
    let { list } = this.state
    if (this.checkedStatus) return
    if (!canSelect) return
    this.checkedStatus = true
    if (this.checkedStatus) {
      Taro.showLoading({
        title: '加载中'
      })
    }
    const { couponItemIds, checkedConpun, selectStore } = this.state
    const index = couponItemIds.findIndex(val => val === coupon.id)
    if (index === -1) {
      checkedConpun.push(coupon)
      couponItemIds.push(coupon.id)
    } else {
      checkedConpun.splice(index)
      couponItemIds.splice(index, 1)
    }
    this.setState({
      couponItemIds
    }, () => this.getPromotion(selectStore.storeCode || list.latelyStoreInfo.storeCode))
  }

  // 打开优惠券弹窗
  openCoupon = () => {
    this.setState({
      useCouponIndex: 0,
      showCouponPop: true
    })
  }

  // 订单详情
  handleToDetials = () => {
    let { orderDetails } = this.state
    this.setState({
      showPaySuc: false
    })
    Taro.redirectTo({
      url: '/pages/order/details/index?orderNumber=' + orderDetails.orderNumber
    })
  }

  // 去预约
  handleToBooking = () => {
    this.setState({
      showPaySuc: false
    })
    const { orderDetails } = this.state
    let { orderNumber, items } = orderDetails
    let goods = []
    if (items) {
      goods = items.goods.map(v => {
        const { goodsId, goodsSkuId, number, type } = v
        return {
          goodsId,
          goodsSkuId,
          number,
          type
        }
      })
    }
    Taro.redirectTo({
      url: `/pages/order/details/index?orderNumber=${orderNumber}&order=${JSON.stringify(goods)}`
    })
  }

  // 点击确认年卡协议
  onChecked = async (total) => {
    const { store = {}, car } = this.props
    const { firstChecked, radioChecked, list, ancardReturn, shareVendorName = '', storeName = '', shareStoreCode = '', selectStore, address } = this.state
    const { mobile } = Taro.getStorageSync('IS_USERINFO')
    const STORE_LOCATION = Taro.getStorageSync('STORE_LOCATION')
    // 门店信息  有路由带code用路由门店code，没有取redux/storage缓存数据
    let nowStore = store || selectStore || STORE_LOCATION
    console.log('address', address)
    if (firstChecked) {
      if (!address && !selectStore.storeCode) {
        Taro.showToast({
          title: '请先选择下单门店！',
          icon: 'none',
          duration: 2000
        })
        this.createOrderStatus = false
        return
      }
      if (!car) {
        Taro.showToast({
          title: '请先添加默认车辆！',
          icon: 'none',
          duration: 2000
        })
        this.createOrderStatus = false
        return
      }
      const obj = {
        path: '/annual-review/annual-card',
        storeName: nowStore.storeName,
        vendorName: nowStore.vendorName,
        carLicense: car.carLicense,
        carId: car.id,
        mobile,
        // shop: JSON.stringify(list.items),
        validDay: list.vailDay,
        total,
        operation: JSON.stringify(ancardReturn) == '{}' ? true : false,
        confirm_sign: ancardReturn.confirm_sign ? ancardReturn.confirm_sign : "",
        time: ancardReturn.time ? ancardReturn.time : "",
        annualCardId: this.$instance.router.params.annualCardId
      }
      console.log('shareVendorName', shareVendorName)
      if (shareVendorName) {
        obj.vendorName = shareVendorName
        obj.storeCode = shareStoreCode
        obj.storeName = storeName
      } else if (selectStore.storeCode) {
        obj.vendorName = selectStore.vendorName
        obj.storeCode = selectStore.storeCode
        obj.storeName = selectStore.storeName
      }
      console.log('obj', obj)
      Taro.navigateTo({
        url: concatUrl('/pages/order/agreement/index', obj)
      })
    } else {
      this.setState({
        radioChecked: !radioChecked,
      })
    }
  }
  changeOrderStore = () => {
    let { selectStore, list } = this.state
    console.log(this.state)
    selectStore.storeName = list.latelyStoreInfo.storeName
    selectStore.storeCode = list.latelyStoreInfo.storeCode

    this.setState({
      selectStore,
      noOprate: false
    }, async () => {
      await this.getList() // 获取订单数据
      await this.getPromotion(selectStore.storeCode)
    })
  }

  // 选择下单区域
  gotoSelectArea() {
    Taro.navigateTo({
      url: `/pages/platform/city/index?type=1`
    })
  }

  // 选择下单门店
  gotoSelectStores() {
    const { list, selectStore } = this.state
    let { jihuasuanId, jihuasuanSource } = this.$instance.router.params

    let { cartList } = list
    console.log('list', list)
    console.log('items', cartList)
    let goodsIds = []
    if (cartList && cartList.length !== 0) {
      goodsIds = cartList.map(v => {
        const { id } = v.goods
        return id
      })
    }
    let url = jihuasuanId ? `/pages/store/platform/index?goodsIds=${String(goodsIds)}&jihuasuanId=${jihuasuanId}&jihuasuanSource=${jihuasuanSource}` : `/pages/store/platform/index?goodsIds=${String(goodsIds)}`
    if (selectStore.storeCode) {
      url = jihuasuanId ? `/pages/store/platform/index?goodsIds=${String(goodsIds)}&cityCode=${selectStore.cityCode}&jihuasuanId=${jihuasuanId}&jihuasuanSource=${jihuasuanSource}` : `/pages/store/platform/index?goodsIds=${String(goodsIds)}&cityCode=${selectStore.cityCode}`
    }
    console.log('url', url)
    console.log('goodsIds', goodsIds)
    Taro.navigateTo({
      url
    })
  }
  // 年卡下单选择下单门店
  gotoSelectAnnaulStores() {
    let { jihuasuanId, jihuasuanSource } = this.$instance.router.params
    const { list, selectStore } = this.state
    let { cityCode = '', isTopicAnnualCard = 0, annualCardId } = this.$instance.router.params
    console.log('this.$instance.router.params', this.$instance.router.params)
    console.log('list', list)
    let url = jihuasuanId ? `/pages/store/platform/index?annualCardId=${list.annualCardId}&type=annual&isTopicAnnualCard=${isTopicAnnualCard}&jihuasuanId=${jihuasuanId}&jihuasuanSource=${jihuasuanSource}` : `/pages/store/platform/index?annualCardId=${list.annualCardId}&type=annual&isTopicAnnualCard=${isTopicAnnualCard}`
    if (selectStore.storeCode) {
      url = `/pages/store/platform/index?annualCardId=${list.annualCardId}&cityCode=${selectStore.cityCode || ''}&type=annual&isTopicAnnualCard=${isTopicAnnualCard}`
      if (jihuasuanId) {
        url = `/pages/store/platform/index?annualCardId=${list.annualCardId}&cityCode=${selectStore.cityCode || ''}&type=annual&isTopicAnnualCard=${isTopicAnnualCard}&jihuasuanId=${jihuasuanId}&jihuasuanSource=${jihuasuanSource}`
      }
    }
    if (cityCode) {
      url = `/pages/store/platform/index?annualCardId=${list.annualCardId}&cityCode=${cityCode || ''}&type=annual&isTopicAnnualCard=${isTopicAnnualCard}`
      if (jihuasuanId) {
        url = `/pages/store/platform/index?annualCardId=${list.annualCardId}&cityCode=${cityCode || ''}&type=annual&isTopicAnnualCard=${isTopicAnnualCard}&jihuasuanId=${jihuasuanId}&jihuasuanSource=${jihuasuanSource}`
      }
    }
    Taro.navigateTo({
      url
    })
  }
  // 点击跳转年卡协议
  goLicenses = (total) => {
    const { store = {}, car } = this.props
    const { list, ancardReturn, shareVendorName = '', storeName = '', shareStoreCode = '', selectStore, address } = this.state
    const { mobile } = Taro.getStorageSync('IS_USERINFO')
    const STORE_LOCATION = Taro.getStorageSync('STORE_LOCATION')
    // 门店信息  有路由带code用路由门店code，没有取redux/storage缓存数据
    let nowStore = store || selectStore || STORE_LOCATION
    console.log('address', address)
    if (!address && !selectStore.storeCode) {
      Taro.showToast({
        title: '请先选择下单门店！',
        icon: 'none',
        duration: 2000
      })
      this.createOrderStatus = false
      return
    }
    if (!car) {
      Taro.showToast({
        title: '请先添加默认车辆！',
        icon: 'none',
        duration: 2000
      })
      this.createOrderStatus = false
      return
    }
    console.log('car', car)
    const obj = {
      path: '/annual-review/annual-card',
      storeName: nowStore.storeName,
      vendorName: nowStore.vendorName,
      carLicense: car.carLicense,
      carId: car.id,
      mobile,
      // shop: JSON.stringify(list.items),
      validDay: list.vailDay,
      total,
      operation: JSON.stringify(ancardReturn) == '{}' ? true : false,
      confirm_sign: ancardReturn && ancardReturn.confirm_sign ? ancardReturn.confirm_sign : "",
      time: ancardReturn && ancardReturn.time ? ancardReturn.time : "",
      annualCardId: this.$instance.router.params.annualCardId
    }
    if (shareVendorName) {
      obj.vendorName = shareVendorName
      obj.storeCode = shareStoreCode
      obj.storeName = storeName
    }
    Taro.navigateTo({
      url: concatUrl('/pages/order/agreement/index', obj)
    })
  }

  handleToDetials() {
    this.setState({
      showPaySuc: false
    })
    const prevRouteLink = prevRoute()
    if (prevRouteLink && prevRouteLink.indexOf('pages/order/details/index') > -1) {
      Taro.navigateBack()
      return
    }
    Taro.redirectTo({
      url: '/pages/order/details/index?orderNumber=' + this.$instance.router.params.orderNumber
    })
  }

  render() {
    const { cardTips, isOpened, selectStore, isCheck, list, noOprate, listLoaded, down, promotion, payList, payMethod, showPayPop, useCouponIndex, showCouponPop, couponItemIds, checkedConpun, customerRemark, showPaySuc, distribution, radioChecked, shareMobile, address, storeName, shareOpenString, openedModal, isCarMaintain, maintainCarInfo } = this.state
    console.log('storeName', storeName)
    console.log('selectStore', selectStore)
    const { store, user } = this.props
    const STORE_LOCATION = Taro.getStorageSync('STORE_LOCATION')
    let CURRENT_LOCATION_INFO = Taro.getStorageSync('CURRENT_LOCATION_INFO')
    const type = this.$instance.router.params.type ? this.$instance.router.params.type : 0
    let staffCode = this.$instance.router.params.staffCode || ''
    const isAnnaul = type > 0
    const hasChecked = couponItemIds.length > 0

    // 门店信息  有路由带code用路由门店code，没有取redux/storage缓存数据
    let nowStore = store ? store : STORE_LOCATION
    let loadedPayList = false
    if (payList.length) {
      loadedPayList = true
    }
    //页面显示价格相关信息
    const priceMsg: any = {
      total: 0,// 实付
      coupon: 0,// 卡券，优惠券
      redPacket: 0,// 红包
      superRedPacket: 0,// 超级红包
      baobeiRedPacket: 0, //保呗红包
      platformRedPacket: 0, // 平台红包
      labor: 0,// 工时费
      discount: 0,// 折扣
    }
    let cartList = []
    if (isAnnaul) {
      cartList = list.items
      priceMsg.total = Number(list.price)
      if (list.totalLaborFee) {
        priceMsg.labor = list.totalLaborFee
        priceMsg.total += priceMsg.labor
      }
      priceMsg.total = priceMsg.total.toFixed(2)
    } else {
      cartList = list.cartList
      if (list.totalPrice) {
        priceMsg.total = list.totalPrice
        cartList.map((v: any) => {
          priceMsg.labor += Number(v.goods.laborFee)
        })
        if (promotion) {
          console.log('promotion', promotion)
          priceMsg.coupon = promotion.coupon.discountPrice
          if (isCheck) {
            priceMsg.redPacket = promotion.redPacket
            priceMsg.superRedPacket = promotion.superRedPacket
            priceMsg.baobeiRedPacket = promotion.baobeiRedPacket
            priceMsg.platformRedPacket = promotion.platformRedPacket
          } else {
            priceMsg.redPacket = 0
            priceMsg.superRedPacket = 0
            priceMsg.baobeiRedPacket = 0
            priceMsg.platformRedPacket = 0
          }
          priceMsg.total = Number(priceMsg.total) - Number(priceMsg.coupon) - Number(priceMsg.redPacket) - Number(priceMsg.superRedPacket) - Number(priceMsg.baobeiRedPacket) - Number(priceMsg.platformRedPacket) - Number(distribution.reductionPriceNumber) - Number(promotion.activityPrice)
          priceMsg.discount
        }
        console.log(' priceMsg.total', priceMsg.total)
        priceMsg.total = Number(priceMsg.total) + priceMsg.labor
        priceMsg.total = priceMsg.total.toFixed(2)
        priceMsg.discount = promotion && promotion.activityPrice ? Number(promotion.activityPrice) + Number(distribution.reductionPriceNumber) : Number(distribution.reductionPriceNumber) //折扣
      }
    }
    if (!down && cartList) {
      if (cartList.length > 3) {
        cartList = cartList.slice(0, 3)
      }
    }
    let jihuasuanId = this.$instance.router.params.jihuasuanId || ''
    let paySuccessDialogView = <View className='pay-success-dialog'>
      <View className='content'>
        <View className='mask' onClick={this.handleToDetials.bind(this)}></View>
        <View className='content-wrap'>
          <View className='content-wrap-h'>
            <Image className='icon' src={iconSuc}></Image>
            <View className='content-wrap-h-r'>
              <Text className='text1'>下单成功</Text>
              <Text className='text2'>感谢您的购买！</Text>
            </View>
          </View>
          <View className='content-wrap-tips'>
            为了节省您到店等待时间，请提前预约
          </View>
          <View className='content-wrap-action'>
            <View onClick={this.handleToBooking.bind(this)} className='content-wrap-action-btn'>
              去预约
            </View>
            <View onClick={this.handleToDetials.bind(this)} className='content-wrap-action-btn2'>
              以后再说
            </View>
          </View>
        </View>
      </View>
    </View>
    return (
      <View className='order-index'>
        <AtToast
          isOpened={isOpened}
          text={cardTips}
          duration={2000}
          hasMask={false}>
        </AtToast>
        {console.log('listlistlistlistlist', list)}
        {isCarMaintain ? <CarInfo loaded disabled styleView='4' extra={{ ...maintainCarInfo, showUserInfo: true }} /> : <CarInfo loaded disabled styleView='3' />}
        {showPaySuc && paySuccessDialogView}
        {
          list.items && <View className='goods-item margin-top20'>
            <View className='annual-name'>
              <View className='goods-name'>{list.annualCardName}</View>
              {
                list.vailDay && <View className='vailday'>
                  <View className='span'>{list.vailDay}天</View>
                  <View className='tips'>有效期</View>
                </View>
              }
            </View>
            {
              cartList && cartList.length > 0 && cartList.map((v: any) => {
                return <View key={v.goodsId} className='li'><GoodList list={v} /></View>
              })
            }
            {
              list.items.length > 3 && <MoreView handle={this.changeGoodsStatus.bind(this)} />
            }
          </View>
        }
        {
          list.cartList && <View className='goods-item margin-top20'>
            {
              cartList.map((v) => {
                return <View key={v.id} className='li'><GoodList unit={isCarMaintain && !selectStore.storeCode ? '起' : ''} list={v} /></View>
              })
            }
            {
              list.cartList.length > 3 && <MoreView handle={this.changeGoodsStatus.bind(this)} />
            }
          </View>
        }
        <View className='margin-top20'>
          {
            payList.length > 1 ? (
              <View className='pay-wrap'>
                {
                  payList[payMethod].value === 'offline' ? <View className='offline-tips'>到店支付：0元下单，到店服务再付款。</View> : null
                }
                <StateList name='支付方式' context={
                  <View className='list-wrap'>
                    {
                      loadedPayList && payList.map((v, payIdx) => {
                        return (
                          <View key={v.value} onClick={() => this.changePayIndex(payIdx)} className={classnames('list', payMethod === payIdx && 'curr')}>
                            {v.label}
                            <Image className='check' src={checkIcon}></Image>
                          </View>
                        )
                      })
                    }
                  </View>
                } />
              </View>
            ) :
              (<View className='pay-wrap'><StateList name='支付方式' context={payList.length > 0 && payList[payMethod].label} /></View>)
          }
          {storeName && <StateList name='服务提供方' contextColor='#ff3b30' context={storeName} />}
          {address && <StateList name='门店地址' baseline context={address} contextIconColor='#12B3FF' contextIconSize='44' contextIcon='icon-zu28' />}
          {!storeName && !isAnnaul && <StateList handle={this.gotoSelectStores.bind(this)} name='服务提供方' contextColor='#ff3b30' context={selectStore.storeName || list.latelyStoreInfo && list.latelyStoreInfo.storeName || '请选择下单门店'} contextIcon='icon-shaixuanxialajiantou' />}
          {!storeName && isAnnaul && <StateList handle={this.gotoSelectAnnaulStores.bind(this)} name='服务提供方' contextColor='#ff3b30' context={selectStore.storeName || '请选择下单门店'} contextIcon='icon-shaixuanxialajiantou' />}

          {!address && !!selectStore.address || list.latelyStoreInfo && list.latelyStoreInfo.address && <StateList name='门店地址' baseline context={selectStore.address || list.latelyStoreInfo && list.latelyStoreInfo.address} contextIconColor='#12B3FF' contextIconSize='44' contextIcon='icon-zu28' />}
          {!address && isAnnaul && selectStore.address && <StateList name='门店地址' baseline context={selectStore.address} contextIconColor='#12B3FF' contextIconSize='44' contextIcon='icon-zu28' />}
        </View>
        {
          !!selectStore.cityName && isAnnaul && !storeName && !staffCode && !jihuasuanId && <View className='annual-area-tips'>	此年卡支持在{selectStore.cityName}内可选的门店通用</View>
        }

        {
          jihuasuanId && selectStore.cityCode && CURRENT_LOCATION_INFO && CURRENT_LOCATION_INFO.adCode != selectStore.cityCode ?
            <View className='annual-area-tips'>
              <View> 温馨提示：该门店与你所在位置不在同一个城市，</View>
              <View>请仔细确认下单门店。</View>
            </View>
            : null
        }
        {
          jihuasuanId && CURRENT_LOCATION_INFO && selectStore.cityCode && CURRENT_LOCATION_INFO.adCode == selectStore.cityCode && selectStore.distance && selectStore.distance >= 30 ?
            <View className='annual-area-tips'>
              <View>温馨提示：该门店与你所在距离较远，</View>
              <View>请仔细确认下单门店。</View>
            </View>
            : null
        }


        <View className={classnames('pop-container', showPayPop && 'show')} onTouchMove={(e) => { e.stopPropagation() }}>
          <View className='mask'></View>
          <View className='pop-cont'>
            <View className='pop-title-hd'><View onClick={() => this.setState({ showPayPop: false })} className='cancel-btn'>取消</View><View className='name'>请选择支付方式</View></View>
            <View className='pop-cont-bd'>
              <View className='list-wrap'>
                {
                  loadedPayList && payList.map((v, payIdx) => {
                    return (
                      <View key={v.value} onClick={() => this.changePayIndex(payIdx)} className={classnames('list', payMethod === payIdx && 'curr')}>
                        {v.label}
                        <Image className='check' src={checkIcon}></Image>
                      </View>
                    )
                  })
                }
              </View>
              <View onClick={() => this.setState({ showPayPop: false })} className='pop-confirm-btn'>确定</View>
            </View>
          </View>
        </View>
        {
          !jihuasuanId && promotion && (
            <View className='margin-top20'>
              <StateList name='卡券红包' color='#333' border />
              {
                checkedConpun.length > 0 ? (
                  <View className='msg'>
                    {
                      checkedConpun.length == 1 ? <StateList handle={this.openCoupon.bind(this)} image={couponIcon} name='卡券' context={checkedConpun[0].name} contextIcon='icon-shaixuanxialajiantou' /> :
                        <StateList handle={this.openCoupon.bind(this)} image={couponIcon} name='卡券' context={`已选${checkedConpun.length}张`} contextIcon='icon-shaixuanxialajiantou' />
                    }
                    {
                      (promotion.redPacket > 0 || promotion.superRedPacket > 0 || promotion.baobeiRedPacket > 0 || promotion.platformRedPacket > 0) ? <StateList image={redpacketIcon} name='红包' context={'优惠 ￥' + (accAdd(accAdd(Number(promotion.redPacket), Number(promotion.superRedPacket)), accAdd(Number(promotion.baobeiRedPacket), Number(promotion.platformRedPacket))))} checked={isCheck} change={this.changeCheck.bind(this)} /> :
                        <StateList image={redpacketIcon} name='红包' context='暂无可用' />
                    }
                  </View>
                ) : (
                  <View className='msg'>
                    {
                      promotion.coupon.available.length > 0 ? <StateList handle={this.openCoupon.bind(this)} image={couponIcon} name='卡券' context={'有' + promotion.coupon.available.length + '张优惠券可用'} contextIcon='icon-shaixuanxialajiantou' /> :
                        <StateList image={couponIcon} name='卡券' context='暂无可用' />
                    }
                    {
                      (promotion.redPacket > 0 || promotion.superRedPacket > 0 || promotion.baobeiRedPacket > 0 || promotion.platformRedPacket > 0) ? <StateList image={redpacketIcon} name='红包' context={'优惠 ￥' + (accAdd(accAdd(Number(promotion.redPacket), Number(promotion.superRedPacket)), accAdd(Number(promotion.baobeiRedPacket), Number(promotion.platformRedPacket))))} checked={isCheck} change={this.changeCheck.bind(this)} /> :
                        <StateList image={redpacketIcon} name='红包' context='暂无可用' />
                    }
                  </View>
                )
              }
            </View>
          )
        }

        <View className={classnames('pop-container', showCouponPop && 'show')} onTouchMove={(e) => { e.stopPropagation() }}>
          <View className='mask'></View>
          <View className='pop-cont coupon'>
            <View className='pop-title-hd'><View onClick={() => this.setState({ showCouponPop: false })} className='cancel-btn'>取消</View><View className='name'>卡券</View></View>
            <View className='tab-item'>
              <View onClick={() => this.tabCouponTag(0)} className={classnames('tab-li', useCouponIndex === 0 && 'act')}><View className='tab-li-text'>可用卡券({promotion && promotion.coupon.available && promotion.coupon.available.length})</View></View>
              <View onClick={() => this.tabCouponTag(1)} className={classnames('tab-li', useCouponIndex === 1 && 'act')}><View className='tab-li-text'>不可用卡券({promotion && promotion.coupon.disabled && promotion.coupon.disabled.length})</View></View>
            </View>
            <View className='pop-cont-bd'>
              {
                promotion && (
                  <ScrollView scrollY className='coupon-scroll'>
                    {
                      useCouponIndex === 0 && promotion.coupon.available.map(v => {
                        let isChecked = false
                        if (couponItemIds.includes(v.id)) {
                          isChecked = true
                        }
                        const isCouldSelected = v.isCouldSelected == 1
                        return (
                          <View key={v.id} onClick={() => this.checkedCoupon(v, isCouldSelected)} className={classnames('list', !isCouldSelected && 'gray', isChecked && 'curr')}>
                            <CouponView style='2' list={v} />
                            <Image src={checkIcon} className='check'></Image>
                          </View>
                        )
                      })
                    }
                    {
                      useCouponIndex === 1 && promotion.coupon.disabled.map(v => {
                        return (
                          <View key={v.id} className='list gray'>
                            <CouponView style='2' list={v} />
                            <Image src={checkIcon} className='check'></Image>
                          </View>
                        )
                      })
                    }
                  </ScrollView>
                )
              }
              <View onClick={() => {
                if (!hasChecked) return
                this.setState({ showCouponPop: false })
              }} className={classnames('pop-confirm-btn', !hasChecked && 'disabled')}
              >确定</View>
            </View>
          </View>
        </View>

        {
          listLoaded && (
            <View className='margin-top20'>
              <StateList name='订单金额' color='#333' border context={'¥' + (list.totalPrice || list.price)} contextColor='#FF3C31' />
              {priceMsg.coupon ? <StateList name='卡券' context={`-¥${priceMsg.coupon}`} contextColor='#67C23A' /> : null}
              {priceMsg.redPacket ? <StateList name='红包' context={`-¥${(Number(priceMsg.redPacket))}`} contextColor='#67C23A' /> : null}
              {priceMsg.superRedPacket ? <StateList name='超级红包' context={`-¥${Number(priceMsg.superRedPacket)}`} contextColor='#67C23A' /> : null}
              {priceMsg.baobeiRedPacket ? <StateList name='保呗红包' context={`-¥${Number(priceMsg.baobeiRedPacket)}`} contextColor='#67C23A' /> : null}
              {priceMsg.platformRedPacket ? <StateList name='平台红包' context={`-¥${Number(priceMsg.platformRedPacket)}`} contextColor='#67C23A' /> : null}
              <StateList name='折扣' context={`-¥${priceMsg.discount}`} contextColor='#666666' />
              {
                priceMsg.labor != 0 ? <StateList name='工时费' context={`¥${priceMsg.labor.toFixed(2)}`} contextColor='#666666' /> : null
              }

            </View>
          )
        }

        <View className='margin-top20'>
          <View className='text-area-warp'>订单备注</View>
          <View className='text-area'>
            <Textarea value={customerRemark} onInput={this.importMark.bind(this)} className='text' autoHeight placeholder-style='font-size: 30rpx;color: #999' placeholder='在这里输入你对门店的嘱咐，例如：10点左右到、第二天提车...' />
          </View>
          {/*  */}
        </View>
        <View className='handle-cont'>
          {/* 年卡协议  年卡订单才显示 */}
          {
            isAnnaul && !jihuasuanId && <View className="handle-cont-annual">
              <View>
                <Image src={radioChecked ? Checked : Unselected} className="handle-cont-annual-img" onClick={() => this.onChecked(priceMsg.total)} />
              </View>
              <Text>提交订单前请阅读并确认</Text><Text className="handle-cont-annual-point" onClick={() => this.goLicenses(priceMsg.total)}>《年卡协议》</Text>
            </View>
          }
          <View className="handle-cont-pay">
            <View className='price'>实付：<View className='strong'>{priceMsg.total}</View><Text className='unit'>{isCarMaintain && !selectStore.storeCode ? '起' : ''}</Text></View>
            {
              // 年卡订单按钮
              isAnnaul && !storeName && !jihuasuanId && <View className={radioChecked && selectStore.storeCode ? 'btn' : '.btn-forbidden'} onClick={this.sendOrder.bind(this, false)}>提交订单</View>
            }
            {
              // 年卡订单按钮年卡分销
              isAnnaul && storeName && !jihuasuanId && <View className={radioChecked ? 'btn' : '.btn-forbidden'} onClick={this.sendOrder.bind(this, false)}>提交订单</View>
            }
            {
              // 非年卡订单按钮
              !isAnnaul && !jihuasuanId && <View className='btn' onClick={this.sendOrder.bind(this, false)}>提交订单</View>
            }
            {
              // 非年卡订单按钮
              isAnnaul && jihuasuanId && <View className='btn' onClick={this.sendOrder.bind(this, false)}>提交订单</View>
            }
            {
              // 集划算非年卡
              !isAnnaul && jihuasuanId && <View className='btn' onClick={this.sendOrder.bind(this, false)}>提交订单</View>
            }
          </View>
          {/*
					 */}
        </View>
        <AtModal isOpened={openedModal}>
          <AtModalHeader>请确认您的下单门店</AtModalHeader>
          <AtModalContent>
            {
              selectStore.logo && <Image style='height:150px' mode='aspectFill' src={selectStore.logo}></Image>
            }

            <View className='store-modal'>
              <View className='left'>
                <View className='store-name'>{selectStore.storeName || list.latelyStoreInfo && list.latelyStoreInfo.storeName}</View>
                <View className='store-address'>{selectStore.address || list.latelyStoreInfo && list.latelyStoreInfo.address}</View>
                {
                  selectStore.distance && <View className={classnames('store-tips', Number(selectStore.distance) > 30 && 'warning')}>距您{selectStore.distance}km，请您确认下单门店</View>
                }
              </View>
              <View className='right' onClick={type > 0 ? this.gotoSelectAnnaulStores.bind(this) : this.gotoSelectStores.bind(this)}>修改</View>
            </View>

          </AtModalContent>
          <AtModalAction> <Button onClick={this.closeOpenedModal.bind(this, true)}>取消</Button> <Button onClick={this.sendOrder.bind(this, true)}>确定</Button> </AtModalAction>
        </AtModal>
      </View >
    )
  }
}
